<script setup>
import { onMounted, nextTick, ref, reactive, watch, computed, watchEffect } from 'vue'
import closeIcon from '../assets/img/close.png'
import { formatTime } from '../utils/cTime.js'
import { SaveState, getBargeShip, getFisherShip, upload, getArea, addDisposalRecord } from '../network/net.js'
import chun from '../stores/chun.js'
import {
    Location
} from '@element-plus/icons-vue'
const url = import.meta.env.VITE_backurl;

const imageUrl = ref('')
let fileList = ref([])

onMounted(() => {
    getBargeShip().then(res => {
        if (res.data.code === 200) {
            bargeShips.value = res.data.data.map(item => {
                return {
                    value: item.name,
                    label: item.name,
                }
            })
            chun.bargeShips = bargeShips.value
        }
    }).catch(err => {
        console.log(err)
    })

    getFisherShip().then(res => {
        if (res.data.code === 200) {
            fisherShips.value = res.data.data.map(item => {
                return {
                    value: item.name,
                    label: item.name,
                    seaArea: item.seaArea
                }
            })
            chun.fisherShips = fisherShips.value
        }
    }).catch(err => {
        console.log(err)
    })

    getArea().then(res => {
        if (res.data.code === 200) {
            areas.value = res.data.data.map(item => {
                return {
                    value: item.name,
                    label: item.name
                }
            })
        }
    }).catch(err => {
        console.log(err)
    })

    const now = new Date();

    // 使用getFullYear, getMonth (注意月份是从0开始的，所以要+1), getDate, getHours, getMinutes方法  
    // 并且将它们格式化为字符串来拼接成你想要的格式  
    const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}T${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    currentDate.value = [now.getFullYear().toString(), (now.getMonth() + 1).toString().padStart(2, '0'), now.getDate().toString().padStart(2, '0')]
    currentTime.value = [now.getHours().toString().padStart(2, '0'), now.getMinutes().toString().padStart(2, '0')]
    formInfo.value[0].value = formattedDate
    formInfo.value[3].value = chun.userInfo.username
    formInfo.value[1].value = chun.userInfo.bargeShip

    formInfoCz.value[0].value = formattedDate
    formInfoCz.value[1].value = chun.userInfo.bargeShip
    formInfoCz.value[2].value = chun.userInfo.username

})
const handleFileChange = (event) => {
    // fileList.value = event.target.files
    // 判断和fileList中是否有重复的文件
    // for (let i = 0; i < event.target.files.length; i++) {
    //     let flag = false
    //     for (let j = 0; j < fileList.value.length; j++) {
    //         if (event.target.files[i].name === fileList.value[j].name) {
    //             flag = true
    //             break
    //         }
    //     }
    //     if (!flag) {
    //         fileList.value.push(event.target.files[i])
    //     }
    // }

    let allP = []
    for (let i = 0; i < event.target.files.length; i++) {
        // 使用upload上传文件
        let formData = new FormData()
        formData.append('file', event.target.files[i])
        allP.push(upload(formData))
    }
    Promise.all(allP).then(res => {
        for (let i = 0; i < res.length; i++) {
            fileList.value.push(res[i].data.data)
            // formInfo.value[7].value += res[i].data.data + ','
        }
    }).catch(err => {
        console.log('上传失败')
    })
}

let disA = ref(false)
const handleSub = () => {
    if (disA.value) {
        return
    }
    disA.value = true
    for (let i = 0; i < formInfo.value.length; i++) {
        formInfo.value[i].value = formInfo.value[i].value.trim() // 去除首尾空格
        if (formInfo.value[i].value === '') {
            alert('请填写完整信息')
            return
        }
    }

    // todo: 提交信息

    let formData = new FormData()
    // for (let i = 0; i < fileList.value.length; i++) {
    //     console.log("filePath"+i);
    //     formData.append("filePath"+i, fileList.value[i])
    // }
    formData.append('pics', fileList.value.join(','))
    for (let i = 0; i < formInfo.value.length; i++) {
        if (formInfo.value[i].key === 'date') {
            formData.append(formInfo.value[i].key, formatTime(formInfo.value[i].value))
        } else {
            formData.append(formInfo.value[i].key, formInfo.value[i].value)
        }
    }
    // state ymState ymText
    formData.append('state', '未录入完成')
    formData.append('ymState', '')
    formData.append('ymText', '')
    formData.append('pics', '')

    console.log(formData.get('num'));


    SaveState(formData).then(res => {
        if (res.data.code === 200) {
            alert('提交成功')
            fileList.value = []
            for (let i = 0; i < formInfo.value.length; i++) {
                formInfo.value[i].value = ''
            }
        } else {
            alert('提交失败')
        }
    }).catch(err => {
        alert('提交失败')
    }).finally(() => {
        const now = new Date();
        const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}T${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        formInfo.value[0].value = formattedDate
        formInfo.value[3].value = chun.userInfo.username
        formInfo.value[1].value = chun.userInfo.bargeShip

        disA.value = false
    })
}

let disCz = ref(false)
const handleSubCz = () => {
    if (disCz.value) {
        return
    }
    disCz.value = true
    for (let i = 0; i < formInfoCz.value.length; i++) {
        formInfoCz.value[i].value = formInfoCz.value[i].value.trim() // 去除首尾空格
        if (formInfoCz.value[i].value === '') {
            alert('请填写完整信息')
            return
        }
    }

    let allData = {
        date: formatTime(formInfo.value[0].value),
        bargeShip: formInfoCz.value[1].value,
        audit: formInfoCz.value[2].value,
        weight: formInfoCz.value[3].value,
        disposalMethod: formInfoCz.value[4].value,
        disposalPosition: formInfoCz.value[5].value
    }

    // allData.date = formatTime

    addDisposalRecord(allData).then(res => {
        if (res.data.code === 200) {
            alert('提交成功')
            for (let i = 0; i < formInfoCz.value.length; i++) {
                formInfoCz.value[i].value = ''
            }
        } else {
            alert('提交失败')
        }
    }).catch(err => {
        alert('提交失败')
    }).finally(() => {
        const now = new Date();
        const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}T${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        formInfoCz.value[0].value = formattedDate
        formInfoCz.value[1].value = chun.userInfo.bargeShip
        formInfoCz.value[2].value = chun.userInfo.username
        formInfoCz.value[4].value = '抛投'

        disCz.value = false
    })

}

// 1.卸载时间：年 月 日 时。
// 2.船号:卸载驳船号、卸载渔船号。
// 3.稽核人员：某某甲、某某乙。
// 4.卸载重量：X吊（磅次）、X千克（kg）。
// 5.打捞海域（作业地点）：如S2-1等。
// 6.处置量：X千克（kg）。
// 7.处置方式：抛投、资源化利用。

// const formInfo = reactive({
//     date: '1',
//     shipNumber: '',
//     audit: '',
//     weight: '',
//     salvageArea: '',
//     disposal: '',
//     disposalMethod: ''
// })

const formInfo = ref([
    {
        label: '卸载时间',
        value: '',
        key: 'date'
    },
    {
        label: '驳船号',
        value: '',
        key: 'bargeShip'
    },
    {
        label: '渔船号',
        value: '',
        key: 'fisherShip'
    },
    {
        label: '稽核人员',
        value: '',
        key: 'audit'
    },
    {
        label: '有效吊装次数',
        value: '',
        key: 'num'
    },
    {
        label: '卸载重量(吨)',
        value: '',
        key: 'weight'
    },
    {
        label: '打捞海域',
        value: '',
        key: 'salvageArea'
    },
    // {
    //     label: '处置量(吨)',
    //     value: '',
    //     key: 'disposal'
    // },
    // {
    //     label: '处置方式',
    //     value: '',
    //     key: 'disposalMethod'
    // }
])

const formInfoCz = ref([
    {
        label: '处置时间',
        value: '',
        key: 'date'
    },
    {
        label: '驳船号',
        value: '',
        key: 'bargeShip'
    },
    {
        label: '操作人员',
        value: '',
        key: 'audit'
    },
    {
        label: '处置量(吨)',
        value: '',
        key: 'weight'
    },
    {
        label: '处置方式',
        value: '抛投',
        key: 'disposalMethod'
    },
    {
        label: '处置位置',
        value: '',
        key: 'disposalPosition'
    },
])
const hq = ref('崂山区')

const bargeShips = ref([])



const fisherShips = ref([
    {
        value: 'bbb',
        label: '船1'
    },
    {
        value: 'bbc',
        label: '船2'
    },
])

// const fisherShipsCom = computed(() => {
//     return fisherShips.value.filter(item => item.label.includes(hq.value))
// })

const areas = ref([
    {
        value: 'bbb',
        label: '船1'
    },
    {
        value: 'bbc',
        label: '船2'
    },
])

const options = reactive({
    '驳船号': [],
    '渔船号': [],
})

const pickerDate = () => {
    formInfo.value[0].value = new Date().toLocaleString()
}

const createObjectURL = (file) => {
    return URL.createObjectURL(file)
}

const handleCF = (fileIdx) => {
    fileList.value = fileList.value.filter((item, idx) => idx !== fileIdx)
}

let fOptions = ref([])
const remoteMethod = (query) => {
    if (query) {
        // fOptions.value = fisherShips.value.filter(item => item.label.includes(query))
        fOptions.value = fisherShips.value.filter(item => item.label.includes(query) && item.seaArea.includes(hq.value))
    } else {
        fOptions.value = []
    }
}

const inputType = ref('卸载')
const ptAreas = ref(['海域1'])

const getLocation = () => {
    navigator.geolocation.getCurrentPosition(success, error, options)

    function success(position) {
        formInfoCz.value[5].value = `纬度：${position.coords.latitude.toFixed(4)}，经度：${position.coords.longitude.toFixed(4)}`

        // formInfoCz.value[5].value = `纬度：${position.coords.latitude.toFixed(4)}，经度：${position.coords.longitude.toFixed(4)}`
    }

    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    }

    var options = {
        enableHighAccuracy: true,
        timeout: 0,
        maximumAge: 0
    };
}

const minDate = new Date(2023, 0, 1);
const maxDate = new Date(2025, 0, 1);
const currentDate = ref(['2024', '01', '01']);
const currentTime = ref(['00', '00']);
const showBottomDate = ref(false);

const timeConfirm = () => {
    let arr = formInfo.value[0].value.split('T')
    arr[0] = currentDate.value.join('-')
    formInfo.value[0].value = arr.join('T')
    showBottomDate.value = false
}

const timeCancel = () => {
    showBottomDate.value = false
}

const showBottomTime = ref(false)
const timeConfirm1 = () => {
    let arr = formInfo.value[0].value.split('T')
    arr[1] = currentTime.value.join(':')
    formInfo.value[0].value = arr.join('T')
    showBottomTime.value = false
}

const timeCancel1 = () => {
    showBottomTime.value = false
}


watch(formInfoCz.value[4], (val) => {
    formInfoCz.value[5].value = ''
})

</script>

<template>
    <div id="input">
        <section class="home_title">
            <span>录入信息</span>
        </section>

        <section id="input_s1">
            <el-radio-group v-model="inputType" style="width: 100%;justify-content: space-around;padding-bottom: 5px;">
                <el-radio value="卸载" size="" border>打捞信息录入</el-radio>
                <el-radio value="处置" size="" border>处置信息录入</el-radio>
            </el-radio-group>
            <template v-if="inputType == '卸载'">
                <div v-for="item in formInfo" class="s1_i">
                    <div class="il"><span style="color: red;">*</span> {{ item.label }}</div>
                    <el-select v-model="item.value" placeholder="请选择" size="" v-if="['驳船号'].includes(item.label)">
                        <el-option v-for="item in (item.label == '驳船号' ? bargeShips : fisherShips)" :key="item.value"
                            :label="item.label" :value="item.value" />
                    </el-select>
                    <!-- 时间选择器 -->
                    <div v-else-if="item.label === '卸载时间'"
                        style="display: flex;align-items: center;justify-content: space-between;height: 38px;">
                        <!-- <input id="h_t" type="datetime-local" v-model="item.value"
                            style="width: 100%;height: 100%;border: none;"> -->
                        <div id="t_p">
                            <div class="p_i" @click="showBottomDate=!showBottomDate">
                                {{ item.value.split('T')[0] }}
                            </div>
                            <div class="p_i" style="margin-left: 10px;" @click="showBottomTime=!showBottomTime">
                                {{ item.value.split('T')[1] }}
                            </div>
                        </div>
                    </div>
                    <!-- 数字输入 -->
                    <el-input v-model="item.value" placeholder="请输入"
                        v-else-if="item.label === '卸载重量(吨)' || item.label === '处置量(吨)'|| item.label === '有效吊装次数'" type="number"></el-input>

                    <el-select v-model="item.value" placeholder="请选择" size="" v-else-if="item.label == '处置方式'">
                        <el-option v-for="item in ['抛投', '资源化利用']" :key="item" :label="item" :value="item" />
                    </el-select>

                    <el-select v-model="item.value" placeholder="请选择" size="" v-else-if="item.label == '打捞海域'">
                        <el-option v-for="item in areas" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>

                    <template v-else-if="item.label == '渔船号'">
                        <div style="display: flex;">
                            <el-select v-model="hq" placeholder="Select" style="width: 190px">
                                <el-option label="崂山区" value="崂山区" />
                                <el-option label="城阳区" value="城阳区" />
                                <el-option label="胶州市" value="胶州市" />
                                <el-option label="西海岸新区" value="西海岸新区" />
                                <el-option label="市直" value="市直" />
                                <el-option label="日照市" value="日照市" />
                            </el-select>
                            <el-select v-model="item.value" filterable remote reserve-keyword placeholder="请输入"
                                :remote-method="remoteMethod">
                                <el-option v-for="item in fOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </div>

                    </template>

                    <el-input v-model="item.value" placeholder="请输入" v-else></el-input>


                </div>

                <label for="file-input" class="blue-button">
                    上传图片
                    <input id="file-input" class="onlyFile" type="file" accept="image/png, image/jpeg"
                        @change="handleFileChange" multiple />
                </label>
                <!-- 显示图片 -->
                <div v-for="(file, fileIdx) in fileList" :key="file"
                    style="border: 1px dashed #dcdfe6;margin-top: 10px;border-radius: 7px;overflow: hidden;">
                    <img :src="closeIcon" alt=""
                        style="position: absolute;top: 5px;right: 5px;z-index: 999;height: 30px;"
                        @click="handleCF(fileIdx)">
                    <img :src="url + file" alt="" style="width: 100%;">
                </div>
            </template>
            <template v-else>
                <div v-for="item in formInfoCz" class="s1_i">
                    <div class="il"><span style="color: red;">*</span> {{ item.label }}</div>
                    <el-select v-model="item.value" placeholder="请选择" size="" v-if="['驳船号'].includes(item.label)">
                        <el-option v-for="item in (item.label == '驳船号' ? bargeShips : fisherShips)" :key="item.value"
                            :label="item.label" :value="item.value" />
                    </el-select>
                    <!-- 时间选择器 -->
                    <div v-else-if="item.label === '处置时间'"
                        style="display: flex;align-items: center;justify-content: space-between;height: 38px;">
                        <input id="h_t" type="datetime-local" v-model="item.value"
                            style="width: 100%;height: 100%;border: none;">
                    </div>
                    <!-- 数字输入 -->
                    <el-input v-model="item.value" placeholder="请输入"
                        v-else-if="item.label === '卸载重量(吨)' || item.label === '处置量(吨)'" type="number"></el-input>

                    <el-select v-model="item.value" placeholder="请选择" size="" v-else-if="item.label == '处置方式'">
                        <el-option v-for="item in ['抛投', '资源化利用']" :key="item" :label="item" :value="item" />
                    </el-select>

                    <template v-else-if="item.label == '处置位置'">
                        <el-select v-model="item.value" placeholder="请选择" size="" v-if="formInfoCz[4].value == '资源化利用'">
                            <el-option v-for="item in areas" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <el-input v-model="item.value" placeholder="请输入" v-else>
                            <template #append>
                                <el-button :icon="Location" @click="getLocation" />
                            </template>
                        </el-input>
                    </template>

                    <el-input v-model="item.value" placeholder="请输入" v-else></el-input>


                </div>
            </template>

        </section>
        <button id="input_b" @click="handleSub" v-if="inputType == '卸载'">
            <span>
                提交
            </span>
        </button>
        <button id="input_b" @click="handleSubCz" v-else>
            <span>
                提交
            </span>
        </button>

        <van-popup v-model:show="showBottomDate" round position="bottom" :style="{ height: '30%' }"
            @click-overlay="timeConfirm">
            <van-date-picker v-model="currentDate" title="选择日期" :min-date="minDate" :max-date="maxDate"
                @confirm="timeConfirm" @cancel="timeCancel" />
        </van-popup>

        <!-- 时间选择弹窗 -->
        <van-popup v-model:show="showBottomTime" round position="bottom" :style="{ height: '30%' }"
            @click-overlay="timeConfirm1">
            <van-time-picker v-model="currentTime" type="time" title="选择时间" @confirm="timeConfirm1"
                @cancel="timeCancel1" />
        </van-popup>


    </div>
</template>

<style lang="less" scoped>
#input {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: end;
    align-items: center;
    padding: 50px 15px 15px 15px;
    background: #E2F4F4;

    :deep(.el-select__selected-item) {
        width: 100%;
    }

    #t_p {

        display: flex;
        align-items: center;
        width: 100%;

        .p_i {
            height: 38px;
            padding: 1px 11px;
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            border-radius: 4px;
            background-color: #ffffff;
            color: #606266;
            display: flex;
            align-items: center;
            flex: 1;
        }
    }

    #input_s1 {
        background: #FFFFFF;
        border-radius: 17px;
        flex: 1;
        width: 100%;
        padding: 15px;
        overflow: auto;

        :deep(.el-input__wrapper) {
            height: 38px;
        }

        :deep(.el-select__wrapper) {
            height: 38px;
        }

        .s1_i {
            height: 75px;

            .il {
                font-size: 16px;
                font-weight: 500;
                letter-spacing: 0.5px;
                height: 25px;
                line-height: 25px;
            }

            #h_t {
                border: none;
                padding: 4px 8px;
                border-radius: 4px;
                box-shadow: 0 0 0 1px #dcdfe6;
                background-color: #ffffff;
            }
        }

    }

    #input_b {
        background: #12BDA7;
        border-radius: 17px;
        padding: 10px 20px;
        margin-top: 15px;
        cursor: pointer;
        width: 100%;
        height: 46px;
        border: none;

        span {
            font-size: 18px;
            font-family: SourceHanSansCN-Medium;
            font-weight: 500;
            letter-spacing: 1px;
            color: #FFFFFF;
        }
    }

    .blue-button {
        background-color: #12BDA7;
        color: white;
        padding: 7px 10px;
        border-radius: 5px;
        cursor: pointer;
        text-align: center;
    }

    .onlyFile {
        display: none;
    }
}
</style>